package com.lw.leetcode.hash.c;

import com.lw.test.util.Utils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 2306. 公司命名
 *
 * @author liw
 * @version 1.0
 * @date 2022/11/23 10:03
 */
public class DistinctNames {

    public static void main(String[] args) {
        DistinctNames test = new DistinctNames();

        // 6
//        String[] ideas = {"coffee", "donuts", "time", "toffee"};

        // 8
//        String[] ideas = {"coffee","donuts","time","toffee", "cime"};

        // 10
//        String[] ideas = {"coffee","donuts","time","toffee", "aime"};

        // 0
//        String[] ideas = {"lack", "back"};

        //
        String[] ideas = Utils.getStrs(50000, 6, 'a', 'h');
        ideas = Arrays.stream(ideas).distinct().toArray(String[]::new);
        Utils.toPrint(ideas);
        System.out.println();
        System.out.println(ideas.length);

        long l = test.distinctNames(ideas);
        System.out.println(l);
    }

    public long distinctNames(String[] ideas) {
        Map<String, Integer> map = new HashMap<>();
        long sum = 0;
        int[][] flags = new int[26][27];
        for (String idea : ideas) {
            int c = idea.charAt(0) - 'a';
            String s = idea.substring(1);
            int v = map.getOrDefault(s, 0) | (1 << c);
            map.put(s, v);
            flags[c][26]++;
        }
        int[] values = new int[26];
        for (int i = 0; i < 26; i++) {
            values[i] = 1 << i;
        }
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            int v = entry.getValue();
            for (int i = 0; i < 26; i++) {
                if ((v & values[i]) == 0) {
                    continue;
                }
                for (int j = i + 1; j < 26; j++) {
                    if ((v & values[j]) == 0) {
                        continue;
                    }
                    flags[i][j]++;
                    flags[j][i]++;
                }
            }
        }
        for (String idea : ideas) {
            int c = idea.charAt(0) - 'a';
            String s = idea.substring(1);
            int v = map.get(s);
            for (int i = 0; i < 26; i++) {
                if ((v & values[i]) == 0) {
                    sum += (flags[i][26] - flags[i][c]);
                }
            }
        }
        return sum;
    }

}
